package com.xiaode.common;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;


public class JwtHelper {
	// 秘钥
	public static final String SECRET = "bfly-xiaode";
	// 签名是有谁生成
	static final String ISSUSER = "zy.accountService";
	// 签名的主题
	static final String SUBJECT = "zy.token";
	// 签名的观众
	static final String AUDIENCE = "user";
	
	static final int year = 0;
	static final int month = 0;
	static final int hour = 0;
	static final int minute = 0;
	static final int second = 0;
	static final int day = 14;
	
	static Algorithm algorithm = Algorithm.HMAC256(SECRET);
	
	@SuppressWarnings("serial")
	static Map<String, Object> map = new HashMap<String, Object>(){{
		put("alg", "HS256");
        put("typ", "JWT");
	}};
	
	public static String createToken(String info){
		try {
		    LocalDateTime l = LocalDateTime.now();
		    Long longtimestamp = l.toInstant(ZoneOffset.ofHours(8)).toEpochMilli() - 30000;
		    Date nowDate = new Date(longtimestamp);
		    // 过期时间：14天
		    Date expireDate = getAfterDate(nowDate, year, month, day, hour, minute, second);
	        
		    String token = JWT.create()
		    	// 设置头部信息 Header
		    	.withHeader(map)
		    	// 设置 载荷 Payload
		    	.withClaim("info", info)
		    	
		        .withIssuer(ISSUSER)
		        .withSubject(SUBJECT)
		        .withAudience(AUDIENCE)
		        // 生成签名的时间 
		        .withIssuedAt(nowDate)
		        // 签名过期的时间 
		        .withExpiresAt(expireDate)
		        // 签名 Signature
		        .sign(algorithm);
		    return token;
		} catch (JWTCreationException exception){
//			exception.printStackTrace();
			return null;
		}
	}
	
	public static String verifyTokenAndGetInfo(String token) {
		try {
		    DecodedJWT jwt = JWT.require(algorithm).withIssuer(ISSUSER).build().verify(token);
		    Map<String, Claim> claims = jwt.getClaims();
		    Claim claim = claims.get("info");
		    return claim.asString();
		} catch (JWTVerificationException exception){
//			exception.printStackTrace();
			return null;
		}
	}
	
	public static Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){
		if(date == null){
			date = new Date();
		}
		
		Calendar cal = new GregorianCalendar();
		
		cal.setTime(date);
		if(year != 0){
			cal.add(Calendar.YEAR, year);
		}
		if(month != 0){
			cal.add(Calendar.MONTH, month);
		}
		if(day != 0){
			cal.add(Calendar.DATE, day);
		}
		if(hour != 0){
			cal.add(Calendar.HOUR_OF_DAY, hour);
		}
		if(minute != 0){
			cal.add(Calendar.MINUTE, minute);
		}
		if(second != 0){
			cal.add(Calendar.SECOND, second);
		}
		return cal.getTime();
	}
	
}
